package com.hjd.shop.mq;

import com.alibaba.fastjson.JSON;
import com.hjd.shop.api.service.UserService;
import com.hjd.shop.constant.UserMoneyState;
import com.hjd.shop.entity.UserMoneyLog;
import com.hjd.shop.pojo.MqEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author: hjd
 * @Date: 2020/10/28 0028 22:00
 * @Des: rockmq监听类
 * 1.首先需要实现RocketMQListener接口 并重写 onMessage方法
 *   PS:RocketMQListener<T> 后面的泛型就是消息的生产者发送过来的消息的类型。
 * 2.其中rocketmq的messageModel（消息模型）需要设置为 广播(MessageModel.BROADCASTING)，
 * 因为当 确认订单 发生异常时，其他服务都需要接收到 mq的消息。
 */
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}",consumerGroup = "${mq.order.consumer.group.name}",
        messageModel = MessageModel.BROADCASTING)
@Slf4j
public class OrderCancelMqListener implements RocketMQListener<MessageExt> {
    @Autowired
    private UserService userService;
    @Override
    public void onMessage(MessageExt message) {
        MqEntity mqEntity = null;
        try {
        //1.解析消息
            String msgId = message.getMsgId();
            String body = new String(message.getBody(), "UTF-8");
            mqEntity = JSON.parseObject(body, MqEntity.class);
            log.info("消息:"+msgId+"接收成功!");
            if(mqEntity.getUserMoney()!=null&&mqEntity.getUserMoney().compareTo(BigDecimal.ZERO)!=0){
                //2.调用服务层的回退金额方法
                log.info("开始回退 用户:"+mqEntity.getUserId()+"的余额!");
                UserMoneyLog userMoneyLog = new UserMoneyLog();
                userMoneyLog.setMoneyLogType(UserMoneyState.REFUND_MONEY.getCode())
                        .setUseMoney(mqEntity.getUserMoney())
                        .setUserId(mqEntity.getUserId())
                        .setOrderId(mqEntity.getOrderId());
                userService.updateUserMoney(userMoneyLog);
                log.info("用户:"+mqEntity.getUserId()+"的余额回退完毕!");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户:"+mqEntity.getUserId()+"的余额回退失败!");
        }

    }
}
